<template>
  <a-table
    rowKey="id"
    size="middle"
    bordered
    :loading="loading"
    :columns="columns"
    :dataSource="tableDataWithTotals"
    :pagination="false"
  >
    <template slot="htmlSlot" slot-scope="text">
      <div v-html="text"></div>
    </template>

    <template slot="imgSlot" slot-scope="text,record">
      <div style="font-size: 12px;font-style: italic;">
        <span v-if="!text">无图片</span>
        <img v-else :src="getImgView(text)" :preview="record.id" alt="" style="max-width:80px;height:25px;"/>
      </div>
    </template>

    <template slot="fileSlot" slot-scope="text">
      <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
      <a-button
        v-else
        ghost
        type="primary"
        icon="download"
        size="small"
        @click="downloadFile(text)"
      >
        <span>下载</span>
      </a-button>
    </template>
  </a-table>
</template>

<script>
import { getAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'CwZzrygzmxbSubTable',
  mixins: [JeecgListMixin],
  props: {
    record: {
      type: Object,
      default: null,
    }
  },
  data() {
    return {
      description: '在职人员工资明细表内嵌列表',
      disableMixinCreated: true,
      loading: false,
      dataSource: [],
      // 需要计算合计的数值字段（共19个）
      totalFields: [
        'postWage', 'xjgj', 'livingAllowance', 'wivingAllowance', 'sanitationFee',
        'hmbt', 'jkbybt', 'healthSubsidies', 'housingSubsidy', 'jcjxj',
        'xjgz', 'ssx', 'ndkhj', 'heatingFee', 'zzyy',
        'zzMonth', 'basePay', 'njtbt', 'njxgz','yyfhj'
      ],
      // 在职/退休标识字段值（根据实际数据调整，若字段值为中文则直接用）
      statusMap: {
        onJob: '在职', // 对应zzTx_dictText字段的“在职”值
        retired: '退休' // 对应zzTx_dictText字段的“退休”值
      },
      columns: [
        {
          title: '年度',
          align: 'center',
          dataIndex: 'year_dictText'
        },
        {
          title: '姓名',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '职称 (职务)',
          align: 'center',
          dataIndex: 'zc',
        },
        {
          title: '在职退休',
          align: 'center',
          dataIndex: 'zzTx_dictText'
        },
        // 数值字段添加格式化
        {
          title: '岗位工资',
          align: 'center',
          dataIndex: 'postWage',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '26年薪级工资',
          align: 'center',
          dataIndex: 'xjgj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '生活性补贴',
          align: 'center',
          dataIndex: 'livingAllowance',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '工作性津贴',
          align: 'center',
          dataIndex: 'wivingAllowance',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '卫生费',
          align: 'center',
          dataIndex: 'sanitationFee',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '回民补贴',
          align: 'center',
          dataIndex: 'hmbt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '艰苦边远补贴',
          align: 'center',
          dataIndex: 'jkbybt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '保健费（测试中心）',
          align: 'center',
          dataIndex: 'healthSubsidies',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '13%房补',
          align: 'center',
          dataIndex: 'housingSubsidy',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '基础绩效奖',
          align: 'center',
          dataIndex: 'jcjxj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '月应发合计',
          align: 'center',
          dataIndex: 'yyfhj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '25年薪级工资',
          align: 'center',
          dataIndex: 'xjgz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2026年发放的十三薪',
          align: 'center',
          dataIndex: 'ssx',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2026年发放的年度考核奖',
          align: 'center',
          dataIndex: 'ndkhj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '取暖费',
          align: 'center',
          dataIndex: 'heatingFee',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2025年在职月份',
          align: 'center',
          dataIndex: 'zzyy',
          customRender: (text) => this.formatNumber(text, 0) // 月份保留整数
        },
        {
          title: '2026年在职月份',
          align: 'center',
          dataIndex: 'zzMonth',
          customRender: (text) => this.formatNumber(text, 0) // 月份保留整数
        },
        {
          title: '年基本工资',
          align: 'center',
          dataIndex: 'basePay',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '年津贴补贴',
          align: 'center',
          dataIndex: 'njtbt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '年绩效工资',
          align: 'center',
          dataIndex: 'njxgz',
          customRender: (text) => this.formatNumber(text)
        },
      ],
      url: {
        listByMainId: '/cw/cwZzrygzmxbTj/queryCwZzrygzmxbByMainId',
      },
    }
  },
  computed: {
    // 带两条合计行的完整数据
    tableDataWithTotals() {
      if (!this.dataSource || this.dataSource.length === 0) return []

      // 深拷贝原始数据，避免污染原数据
      const newData = JSON.parse(JSON.stringify(this.dataSource))
      // 分别计算在职、退休人员的合计
      const onJobTotals = this.calcStatusTotals(this.statusMap.onJob)
      const retiredTotals = this.calcStatusTotals(this.statusMap.retired)

      // 构建“在职”合计行
      const onJobTotalRow = this.buildTotalRow('在职合计', onJobTotals)
      // 构建“退休”合计行
      const retiredTotalRow = this.buildTotalRow('退休合计', retiredTotals)

      // 添加两条合计行到表格底部
      newData.push(onJobTotalRow, retiredTotalRow)
      return newData
    }
  },
  watch: {
    record: {
      immediate: true,
      handler() {
        if (this.record) {
          this.loadData(this.record)
        }
      }
    }
  },
  methods: {
    loadData(record) {
      this.loading = true
      this.dataSource = []
      getAction(this.url.listByMainId, { id: record.id })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || [] // 兼容无数据场景
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 数字格式化通用方法
     * @param text 原始值
     * @param decimal 小数位数（默认2位，月份保留0位）
     */
    formatNumber(text, decimal = 2) {
      const num = Number(text)
      return isNaN(num) ? `0${decimal > 0 ? '.' + '0'.repeat(decimal) : ''}` : num.toFixed(decimal)
    },

    /**
     * 按在职/退休状态计算合计
     * @param status 状态值（在职/退休）
     */
    calcStatusTotals(status) {
      // 初始化合计为0
      const totals = this.totalFields.reduce((obj, field) => {
        obj[field] = 0
        return obj
      }, {})

      // 筛选对应状态的数据并累加
      this.dataSource.forEach(item => {
        if (item.zzTx_dictText === status) { // 匹配在职/退休状态
          this.totalFields.forEach(field => {
            const val = Number(item[field])
            totals[field] += isNaN(val) ? 0 : val
          })
        }
      })

      // 格式化合计结果
      this.totalFields.forEach(field => {
        const decimal = field === 'zzyy' || field === 'zzMonth' ? 0 : 2
        totals[field] = totals[field].toFixed(decimal)
      })

      return totals
    },

    /**
     * 构建合计行
     * @param label 合计行标签（在职合计/退休合计）
     * @param totals 对应状态的合计数据
     */
    buildTotalRow(label, totals) {
      const totalRow = {
        id: `total_${label}_${new Date().getTime()}`, // 唯一ID，避免rowKey重复
        year_dictText: '',
        name: label, // 姓名列显示合计标签
        unit_dictText: '',
        zc: '',
        zzTx_dictText: '',
        // 填充合计字段值
        postWage: totals.postWage,
        xjgj: totals.xjgj,
        livingAllowance: totals.livingAllowance,
        wivingAllowance: totals.wivingAllowance,
        sanitationFee: totals.sanitationFee,
        hmbt: totals.hmbt,
        jkbybt: totals.jkbybt,
        healthSubsidies: totals.healthSubsidies,
        housingSubsidy: totals.housingSubsidy,
        jcjxj: totals.jcjxj,
        xjgz: totals.xjgz,
        ssx: totals.ssx,
        ndkhj: totals.ndkhj,
        heatingFee: totals.heatingFee,
        zzyy: totals.zzyy,
        zzMonth: totals.zzMonth,
        basePay: totals.basePay,
        njtbt: totals.njtbt,
        njxgz: totals.njxgz,
        yyfhj: totals.yyfhj
      }
      return totalRow
    },

    // 空实现方法，避免报错
    downloadFile(text) {},
    getImgView(text) {
      return text
    }
  },
}
</script>

<style scoped>
/* 合计行样式优化，两条合计行区分显示 */
::v-deep .ant-table-tbody tr:nth-last-child(2),
::v-deep .ant-table-tbody tr:last-child {
  background-color: #f5f5f5 !important;
  font-weight: 600 !important;
  text-align: center !important;
  white-space: nowrap !important;
}
/* 在职合计行样式 */
::v-deep .ant-table-tbody tr:nth-last-child(2) {
  border-top: 2px solid #4299e1 !important;
  color: #2563eb !important;
}
/* 退休合计行样式 */
::v-deep .ant-table-tbody tr:last-child {
  border-top: 1px solid #94a3b8 !important;
  color: #475569 !important;
}

/* 表格横向滚动和列宽优化，适配24列表格 */
::v-deep .ant-table-wrapper {
  overflow-x: auto !important;
  min-width: 1600px !important;
}
::v-deep .ant-table-column-title {
  white-space: nowrap !important;
  font-size: 11px !important;
  padding: 8px 4px !important;
}
::v-deep .ant-table-tbody td {
  white-space: nowrap !important;
  font-size: 11px !important;
  padding: 8px 4px !important;
}
::v-deep .ant-table-thead th {
  white-space: nowrap !important;
}
</style>